// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Collections.Generic;
using System.Data;
using System.Text;

namespace SnapObjects.Data
{
    internal abstract class CommandBuilder
    {
        protected readonly DataContext _dataContext;
        private readonly CommandBuilderContext _builderContext;

        protected CommandBuilder(
            DataContext dataContext,
            CommandBuilderContext builderContext)
        {
            _dataContext = dataContext;
            _builderContext = builderContext;
        }

        protected void Init()
        {
            _builderContext.Reset();
        }

        public string BuiltSql => _builderContext.SqlBuilder.ToString();

        public StringBuilder SqlBuilder => _builderContext.SqlBuilder;

        public IReadOnlyList<ResultSetMapping> ResultSetMappings =>
                        _builderContext.ResultSetMappings;

        public ResultSetMapping FirstOrDefaultResultSetMapping =>
                        _builderContext.FirstOrDefaultResultSetMapping;

        protected void AppendSql(string rawSql)
        {
            this.SqlBuilder.Append(rawSql);
        }

        protected void AddResultSetMapping(ResultSetMapping resultSetMapping)
        {
            _builderContext.AddResultSetMapping(resultSetMapping);
        }

        protected void AddParameter(string name,
            object value,
            Type clrType,
            ParameterDirection diretion = ParameterDirection.Input)
        {
            _builderContext.AddParameter(name, value, clrType, diretion);
        }

        protected void AddParameter(string name,
            object value,
            Type clrType,
            ParameterDirection direction,
            string typeName,
            ValueConverter valueConverter)
        {
            _builderContext.AddParameter(name, value, clrType, direction, typeName, valueConverter);
        }

        protected void AddParameters(IEnumerable<IAdoDbParameter> parameters)
        {
            foreach (var parameter in parameters)
            {
                _builderContext.AddParameter(parameter.ParameterName, parameter.Value, parameter.ClrType);
            }
        }

        public IEnumerable<IAdoDbParameter> GetAdoDbParameters()
        {
            return _builderContext.AdoDbParameters;
        }
    }
}
